var that;
const app = getApp();
var remoteUrl = getApp().globalData.remoteurl;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    images: [],
    imageWidth: getApp().globalData.screenWidth / 4 - 20, //适配机型,
    cardTypes: ["饮食", "疾病"],
    cardIndex: 0,
    form_info: '',
    animationData: {},
    animationData2: {},
    changeAddImage:'/images/imageIcon.png',
    topic1:'',
    topic2:'',
    topic3:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    
  },
  checkboxChange: function (e) {
    this.setData({
      cardLabel: e.detail.value
    })
  },
  bindCardChange: function (e) {
    this.setData({
      cardIndex: e.detail.value
    })
  },
  //展开图片栏
  bindAddImage:function(e){
    var animationImageBox = wx.createAnimation({
      duration: 500,
      timingFunction: "linear",
      transformOrigin: "50% 50% 0",
  
      success: function (res) {
        console.log("成功")
      },
      fail: function(res){
        console.log("失败")
      }
    })
    var animationImageBox2 = wx.createAnimation({
      duration: 500,
      timingFunction: "linear",
      transformOrigin: "50% 50% 0",

      success: function (res) {
        console.log("成功")
      },
      fail: function (res) {
        console.log("失败")
      }
    })
    this.animation = animationImageBox
    var before = '/images/imageIcon.png';
    var ImageSrc = this.data.changeAddImage;
    if (ImageSrc == before)
    {
      animationImageBox.height(960+'rpx').step();
      this.setData({
        animationData: animationImageBox.export(),
        changeAddImage:'/images/less.png'
      })
    }
    else{
      animationImageBox.height(460 + 'rpx').step();
      this.setData({
        animationData: animationImageBox.export(),
        changeAddImage: '/images/imageIcon.png'
      })
    }
    this.animation = animationImageBox2
    if (ImageSrc == before) {
      
      animationImageBox2.opacity(1).step();
      this.setData({
        animationData2: animationImageBox2.export(),
      })
      console.log("成功");
    }
    else {
      animationImageBox2.opacity(0).step();
      this.setData({
        animationData2: animationImageBox2.export(),
      })
    }
  },
  //选择话题
  bindAddTopic: function () {
    var app = getApp();
    var topicNumber = app.globalData.topicNumber;
    if (topicNumber >= 3) {
      wx: wx.showToast({
        title: '最多添加3个标签',
        icon: 'none',
        duration: 1000,
        mask: true
      })
    }
    else{
      wx.navigateTo({
        url: '../addtopic/addtopic',
        success: function () {
          console.log('跳转到标签选择页面成功')
        },
        fail: function () {
          console.log('跳转到标签选择页面失败')
        }
      })
    }
  },
  //删除话题
  bindDeteleTopic:function(){
    var app = getApp();
    var topicNumber = app.globalData.topicNumber;
    if (topicNumber == 3){
      this.setData({
        topic3: ''
      });
    }
    if (topicNumber == 2) {
      this.setData({
        topic2: ''
      });
    }
    if (topicNumber == 1) {
      this.setData({
        topic1: ''
      });
    }
    if (app.globalData.topicNumber > 0){
      app.globalData.topicNumber = app.globalData.topicNumber - 1;
    }
  },
  //选择图片
  chooseImage: function () {
    var length = this.data.images.length;
    console.log(length);
    if (length >= 9) {
      wx: wx.showToast({
        title: '图片已达上限或超过上限，请选择减少图片',
        icon: 'none',
        duration: 1500,
        mask: false,
      })
    }
    else {
      // 选择图片
      wx.chooseImage({
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths;
          console.log(tempFilePaths);
          that.setData({
            images: that.data.images.concat(tempFilePaths)
          });
        }
      })
    }
  },
  previewImage: function (e) {
    // 预览图集
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: that.data.images
    });
  },
  delete: function (e) {
    var index = e.currentTarget.dataset.index;
    var images = that.data.images;
    images.splice(index, 1);
    that.setData({
      images: images
    });
  },
  /**
   *表单提交
  */
  formSubmit: function (e) {
    if(!wx.getStorageSync('openstatus')){
      wx:wx.showToast({
        title: '请登录后使用',
        icon: 'none',
        duration: 1500,
      })
    }else if (e.detail.value.title == '' || e.detail.value.information == '') {
      console.log("1");
      wx: wx.showToast({
        title: '内容不能为空',
        icon: 'none',
        duration: 1500,
      })
    }else if(app.globalData.topicNumber==0){
      wx: wx.showToast({
        title: '至少选择一个标签',
        icon: 'none',
        duration: 1500,
      })
    }else {
      if (e.detail.value)
        //发布等待框
        wx: wx.showLoading({
          title: '发布中,请等待',
        })
      //处理标签
      var label = "";
      if (that.data.topic1){
        label += that.data.topic1 + "&"
      } 
      if (that.data.topic2){
        label += that.data.topic2 + "&"
      }
      if (that.data.topic3){
        label += that.data.topic3 + "&"
      }
      console.log(label);
      //贴子种类
      var cardType;
      if (that.data.cardIndex == 0) {
        cardType = "food";
      } else {
        cardType = "disease";
      }
      //时间
      var timestamp = Date.parse(new Date());
      var date = new Date(timestamp);
      console.log(date);
      var openid = wx.getStorageSync("openstatus");
      //请求
      wx: wx.request({
        // url: 'http://remotehost:8080/publishCard',
        url: remoteUrl + 'publishCard',
        data: {
          title: e.detail.value.title,
          cardType: cardType,
          label: label,
          information: e.detail.value.information,
          time: date,
          openid: openid
        },
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        method: 'POST',
        success: function (res) {
          //判断是否有附带图片
          if (that.data.images.length == 0) {
            that.setData({
              form_info: ""
            })
            wx: wx.showToast({
              title: '发布成功',
              icon: 'success',
              duration: 1500,
              success: function (res) {
                wx: setTimeout(function () {
                  wx: wx.switchTab({
                    url: '/pages/diet/index/index',
                  })
                }, 1500)
              },
            })
          } else {
            //上传图片
            for (var i = 0; i < that.data.images.length; i++) {
              wx: wx.uploadFile({
                // url: 'http://remotehost:8080/uploadImage',
                url: remoteUrl + 'uploadImage',
                filePath: that.data.images[i],
                name: 'image',
                header: {
                  "content-type": "multipart/form-data",
                  "content-type": "application/x-www-form-urlencoded"
                },
                formData: { 
                  cardId: res.data,
                  cardType: cardType
                },
                success: function (res) {
                  wx.hideLoading();
                  that.setData({
                    form_info: "",
                    images: ""
                  })
                  wx.showToast({
                    title: '发布成功',
                    icon: "success",
                    duration: 1500,
                    success: function (e) {
                      wx: setTimeout(function () {
                        wx: wx.switchTab({
                          url: '/pages/diet/index/index',
                        })
                      }, 1500)
                    }
                  })
                },
                fail: function (res) {
                  wx.hideLoading();
                  wx: wx.showToast({
                    title: '图片上传失败',
                    icon: 'none',
                    duration: 1500,
                  })
                }
              })
            }
          }
        },
        fail: function (res) {
          wx: wx.showToast({
            title: '网络出错了',
            icon: "none",
            duration: 1500
          })
        },
        complete: function (res) { },
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //this.onLoad();
    var topic1 = this.data.topic1;
    var topic2 = this.data.topic2;
    var topic3 = this.data.topic3;
    var currentTopicName = app.globalData.pulishTopicName;
    var topicNumber = app.globalData.topicNumber;
    
    console.log('每次进入界面的topicName获取值'+currentTopicName);
    //console.log('每次进入界面的topicNumber获取值' +topicNumber);
    if (currentTopicName != ''){
      currentTopicName = '#' + currentTopicName;
      app.globalData.pulishTopicName = '';
      console.log(currentTopicName);
      //console.log('每次进入if的topicNumber获取值' + topicNumber);
      if (topicNumber == 0) {
        this.setData({
          topic1: currentTopicName,
        })
        //console.log('topic1:'+topicNumber);
      }
      if (topicNumber == 1) {
        this.setData({
          topic2: currentTopicName,
        })
        //console.log('topic2:' +topicNumber);
      }
      if (topicNumber == 2) {
        this.setData({
          topic3: currentTopicName,
        })
        //console.log('topic3:' +topicNumber);
      }
      if (app.globalData.topicNumber < 3){
        app.globalData.topicNumber = app.globalData.topicNumber + 1; 
      }
    } 
    //console.log(topicNumber);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
